import { ComponentClass } from 'react'
import { connect } from '@tarojs/redux'
import Taro, { Component, Config } from '@tarojs/taro'
import { SDBody } from 'sudao-ui'
import SDUtils from 'sudao-utils'

import PageProps from '../../../redux'
import { login, logout } from '../../../redux/actions'
import { ACCOUNT_INFO } from '../../../redux/constants'

import './index.less'

type PageState = {}

type PageOwnProps = {}

interface LaunchMainPage {
  props: PageProps & PageOwnProps
}

@connect(({userState}) => ({
  userState
}), (dispatch) => ({
  login(userInfo) {
    dispatch(login(userInfo))
  },
  logout() {
    dispatch(logout())
  }
}))
class LaunchMainPage extends Component {

  config: Config = {
    backgroundColor: '#fff'
  }

  componentDidMount () {
    Taro.showLoading({
      title: '初始化中...'
    })
    const { userName = '', password = '' } = Taro.getStorageSync(ACCOUNT_INFO)
    if (!SDUtils.strIsEmpty(userName) && !SDUtils.strIsEmpty(password)) {
      this.execLogin(userName, password)
    } else {
      setTimeout(() => {
        this.jumpToUnLoginHomePage()
      }, 2000)
    }
  }

  render () {
    return (
      <SDBody sd-class='container' loading={false}>

      </SDBody>
    )
  }

  execLogin = async (userName: string, password: string) => {
    try {
      let accountInfo = await SDUtils.doLogin('/wxmini/portal/auth/login', {
        userName: userName,
        password: password
      })
      const storeInfo = await SDUtils.doGet(`/wxmini/trader/${accountInfo.traderId}`)
      accountInfo.storeInfo = storeInfo
      this.props.login(accountInfo)
      setTimeout(() => {
        this.jumpToHomePage()
      }, 1500)
    } catch (e) {
      setTimeout(() => {
        this.jumpToUnLoginHomePage()
      }, 2000)
    }
  }

  jumpToUnLoginHomePage = () => {   // 进入未登录时的首页
    Taro.hideLoading()
    Taro.reLaunch({
      url: '/pages/launch/home/index'
    })
  }

  jumpToHomePage = () => {        // 进入登录成功的首页
    Taro.hideLoading()
    Taro.reLaunch({
      url: '/pages/tabbar/home/index'
    })
  }

}

export default LaunchMainPage as ComponentClass<PageOwnProps, PageState>
